import {FC, useState} from "react";
import {Button} from "antd";
import {sendEmailCode} from "@/apis/user";
import {ApiConstants} from "@/apis/constants";
import {errorMessage, successMessage} from "../Message";

/**
 * @Description: 发送验证码组件
 * @author zhaojiuyi
 * @date 2023/4/16
 */
interface Props {
    // 设置发送成功后的禁用时长(单位/s)
    time: number,
    // 目的邮箱
    email: string
}

export const MySendCode: FC<Props> = (props) => {
    let {time, email} = props
    const [isSend, setIsSend] = useState<boolean>(false)
    const [disabledTime, setDisabledTime] = useState<number>(0)

    let timer: number // 准备一个定时器

    async function sendHandler() {
        setIsSend(true)
        const {code, msg} = await sendEmailCode(email)
        setIsSend(false)
        if (code === ApiConstants.SUCCESS){
            successMessage("发送成功")
            /* 触发定时器 */
            timer = window.setInterval(() => {
                if (time <= 0) {
                    window.clearInterval(timer)
                }
                setDisabledTime(time--)
            }, 1000)
        }else{
            errorMessage(msg as string)
        }

    }

    return (
        <>
            <Button type="primary" loading={isSend}
                    onClick={sendHandler}
                    disabled={!!disabledTime}>发送验证码{disabledTime <= 0 ? "" : `(${disabledTime})`}</Button>
        </>
    )
}
